import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isPathMatch } from '@/utils/validate'
import { ElMessage } from 'element-plus'
import type { RouteRecordRaw } from 'vue-router'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register', '/writeOff', '/coupons/receive']

const isWhiteList = (path: string) => {
  return whiteList.some((pattern) => isPathMatch(pattern, path))
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.meta.title) {
      store.dispatch('settings/setTitle', to.meta.title)
    }
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        try {
          await store.dispatch('GetInfo')
          const accessRoutes = await store.dispatch('GenerateRoutes')
          accessRoutes.forEach((route: RouteRecordRaw) => {
            if (route.path === '*') {
              route.path = '/:pathMatch(.*)*'
              route.redirect = '/404'
            }
            console.log(route.path, route)
            router.addRoute(route)
          })
          if (accessRoutes.some((route: RouteRecordRaw) => route.path === '/')) {
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          } else {
            if (accessRoutes[0].children.length > 0) {
              next({ path: accessRoutes[0].path + '/' + accessRoutes[0].children[0].path })
            } else {
              next({ path: accessRoutes[0].path })
            }
          }
        } catch (err) {
          ElMessage.error(err as string)
          await store.dispatch('LogOut')
          next({ path: '/' })
        }
      } else {
        if (to.path != '/404') {
          next()
        } else {
          //返回前一个页面
          // router.go(-1)
          next(false)
        }
      }
    }
  } else {
    // 没有token
    if (isWhiteList(to.path)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
